package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.ContractProduct;
import com.itheima.domain.cargo.ContractProductExample;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.ContractProductService;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import com.itheima.web.utils.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
@Slf4j
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    /**
     * 添加、修改
     * <input type="file"  name="productPhoto" >
     */
    // 注入文件上传的工具类
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 货物列表
     * 功能入口：contract-list.jsp 购销合同列表点击货物
     * 请求地址：
     * http://localhost:8080/cargo/contractProduct/list.do?contractId=6
     */
    @RequestMapping("/list")
    public String list(String contractId,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        //1. 根据购销合同id，查询货物
        ContractProductExample cpExample = new ContractProductExample();
        // 根据购销合同id，查询货物
        // select * from co_contract_product where contract_id=?
        cpExample.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(cpExample, pageNum, pageSize);

        //2. 查询货物的厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> allFactory = factoryService.findAll(factoryExample);

        //保存到域中
        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("factoryList", allFactory);
        // 注意：需要传递contract_id到页面，因为下一步保存货物时候，必须要有购销合同id.
        request.setAttribute("contractId", contractId);

        // 转发到货物添加、列表页面
        return "cargo/product/product-list";
    }

    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        // 设置企业信息
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());
        // 判断
        if (StringUtils.isEmpty(contractProduct.getId())) {
            /* 处理文件上传*/
            try {
                if (productPhoto != null) {
                    // http://qgzri2xv9.hd-bkt.clouddn.com/FjIgT_Ol9JKgXNDf1W_0rfU7wT6r
                    String url = "http://" + fileUploadUtil.upload(productPhoto);
                    // 存储上传的图片的url地址
                    contractProduct.setProductImage(url);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list?contractId=" + contractProduct.getContractId();
    }

    /**
     * 进入修改页面
     * http://localhost:8080/cargo/contractProduct/toUpdate.do?id=e
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据id查询货物
        ContractProduct contractProduct = contractProductService.findById(id);

        //查询货物的厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);

        // 保存
        request.setAttribute("contractProduct", contractProduct);
        request.setAttribute("factoryList", factoryList);
        return "cargo/product/product-update";
    }


    /**
     * 货物删除
     * 请求地址：http://localhost:8080/cargo/contractProduct/delete.do
     * 请求参数：
     * id            货物id，用来删除货物
     * contractId    购销合同id，用来跳转到货物列表
     */
    @RequestMapping("/delete")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId=" + contractId;
    }

    /**
     * 进入上传页面
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId) {
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-import";
    }

    /**
     * 上传货物2点击保存，上传货物
     */
    @RequestMapping("/import")
    public String importExcel(String contractId, MultipartFile file) throws Exception {
        //1. 根据上传的excel文件流，创建工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        //2. 获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        //3. 获取总行数
        int rowCount = sheet.getPhysicalNumberOfRows();

        //4. 遍历，从第二行开始遍历
        Row row = null;
        for (int i = 1; i < rowCount; i++) {
            // 从第二行开始，获取每一行
            row = sheet.getRow(i);
            // 创建货物对象，并读取excel数据封装
            ContractProduct cp = new ContractProduct();
            cp.setFactoryName(row.getCell(1).getStringCellValue());
            cp.setProductNo(row.getCell(2).getStringCellValue());
            // 注意：excel在解析时候，单元格是有类型的，数值类型必须要用getNumericCellValue()方法，否则出错
            cp.setCnumber((int) row.getCell(3).getNumericCellValue());
            cp.setPackingUnit(row.getCell(4).getStringCellValue());
            cp.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
            cp.setBoxNum((int) row.getCell(6).getNumericCellValue());
            cp.setPrice(row.getCell(7).getNumericCellValue());
            cp.setProductDesc(row.getCell(8).getStringCellValue());
            cp.setProductRequest(row.getCell(9).getStringCellValue());
            /**
             * 注意： 设置购销合同id、厂家id
             */
            cp.setContractId(contractId);
            // 根据厂家名称获取厂家id
            Factory factory = factoryService.findFactoryIdByFactoryName(cp.getFactoryName());
            if (factory != null) {
                cp.setFactoryId(factory.getId());
            }

            // 保存货物
            contractProductService.save(cp);
        }
        return "redirect:/cargo/contractProduct/list?contractId=" + contractId;

    }


}
